package educrypt.gui.ctr;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import educrypt.database.dao.TextTypeDAO;
import educrypt.gui.view.EditorTextOptionsView;
import educrypt.gui.view.MainView;

public class EditorTextTypeCtr implements ActionListener, Observer {

	public EditorTextOptionsView editorTextOptionsView;
	public TextTypeDAO textTypeDAO;
	

	public EditorTextTypeCtr(MainView view) {
		this.editorTextOptionsView = view.getEditorTextTypeDialog();
		this.textTypeDAO = TextTypeDAO.getInstance();
		this.initializeValues();
	}

	private void initializeValues() {
		List<String> textTypes = this.textTypeDAO.findAll();
		this.editorTextOptionsView.showStoredItems(textTypes);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();
		if (command.equals(EditorTextOptionsView.ADD_ITEM)) {
			String textType = editorTextOptionsView.getNewItem();
			if (!textType.isEmpty()) {
				textTypeDAO.create(textType);
			}
			editorTextOptionsView.removeNewItem();
		}

		if (command.equals(EditorTextOptionsView.REMOVE_ITEM)) {
			String textTypeToRemove = editorTextOptionsView.getSelectedItem();
			this.textTypeDAO.delete(textTypeToRemove);
		}
	}

	@Override
	public void update(Observable o, Object arg) {
		assert o instanceof TextTypeDAO;

		@SuppressWarnings("unchecked")
		List<String> textTypes = (List<String>) arg;
		this.editorTextOptionsView.showStoredItems(textTypes);
	}
}
